
<template>
    <div class="app-container">

        <!-- 表格查询 -->
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="100px">
            <!-- 店铺名称 -->
            <el-form-item label="店铺名称" prop="shopName">
                <el-input
                    v-model="queryParams.shopName"
                    placeholder="请输入店铺名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="会员名称" prop="clientName">
                <el-input
                    v-model="queryParams.clientName"
                    placeholder="请输入会员名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="会员编码" prop="clientCode">
                <el-input
                    v-model="queryParams.clientCode"
                    placeholder="请输入会员编码"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <!-- <el-form-item label="会员级别" prop="clientLevel">
                <el-input
                    v-model="queryParams.clientLevel"
                    placeholder="请输入会员级别"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="商品名称" prop="shopName">
                <el-input
                    v-model="queryParams.shopName"
                    placeholder="请输入商品名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="收货人" prop="clientLevel">
                <el-input
                    v-model="queryParams.clientLevel"
                    placeholder="请输入收货人"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
                <el-input
                    v-model="queryParams.phone"
                    placeholder="请输入手机号码"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="黑名单" prop="blackFlag">
                <el-checkbox v-model="queryParams.blackFlag" /> 
            </el-form-item>
            <el-form-item label="停用" prop="enableFlag">
                <el-checkbox v-model="queryParams.enableFlag" /> 
            </el-form-item> -->
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>
  
        <!-- 表头操作 -->
        <el-row :gutter="10"  class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                >新增</el-button>
            </el-col>
            <!-- <el-col :span="1.8">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleUpload"
                >会员导入</el-button>
            </el-col> -->
            <!-- <el-col :span="2.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    @click="()=>handleChange('bizUser')"
                >批量修改业务员</el-button>
            </el-col> -->

            <!-- <el-col :span="2.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    @click="()=>handleChange('distributor')"
                >批量修改分销商</el-button>
            </el-col> -->

            
            <!-- <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-success"
                    size="mini"
                    @click="()=>handleEnable('Y')"
                >启用</el-button>
            </el-col> -->
            <!-- <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-error"
                    size="mini"
                    @click="()=>handleEnable('N')"
                >停用</el-button>
            </el-col> -->
            
            <!-- <el-col :span="1.5">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    @click="handleDelete"
                >删除</el-button>
            </el-col> -->
            <!-- <right-toolbar @queryTable="getList"></right-toolbar> -->
        </el-row>

        <!-- 表格数据 -->
        <vxe-table
          border
          stripe
          v-loading="loading" 
          ref="tableRef"
          size="small"
          header-align="center"
          :row-config="rowConfig"
          :column-config="columnConfig"
          @checkbox-change="checkboxChangeEvent"
          @checkbox-all="checkboxAll"
          @cell-click="cellClickEvent"
          :data="tableDataList"
        >
          <!-- <vxe-column type="checkbox" width="80" fixed="left" drag-sort /> -->
          <vxe-column type="seq" width="60" align="center" fixed="left" />
          <vxe-column field="clientCode" show-overflow="title" align="center" title="会员编码" />
          <vxe-column field="clientName" show-overflow="title" align="center" title="会员名称"  />
          <!-- <vxe-column field="shopType"  show-overflow="title" align="center" title="会员来源" /> -->
          <!-- <vxe-column field="clientLevel" show-overflow="title" align="center" title="会员级别" /> -->
          <vxe-column field="shopName" show-overflow="title" align="center" title="店铺名称" />
          <vxe-column field="phone" show-overflow="title" align="center" title="手机号" />
          <vxe-column field="remark" show-overflow="title" align="center" title="备注" />
          <!-- <vxe-column field="shopLevel" show-overflow="title" align="center" title="店铺级别" /> -->
          <!-- <vxe-column field="bizUser" show-overflow="title" align="center" title="业务员" /> -->
          <!-- <vxe-column field="distributorDesc" show-overflow="title" align="center" title="分销商" /> -->
          <!-- <vxe-column field="blackDesc" show-overflow="title" align="center" title="黑名单" />
          <vxe-column field="creditCode" show-overflow="title" align="center" title="身份证号" /> -->
          <vxe-column field="createTime"  show-overflow="title" align="center" title="创建时间" />
          <!-- <vxe-column field="updateTime" show-overflow="title" align="center" title="修改时间"  /> -->
          <vxe-column width="180" align="center" title="操作" fixed="right">
              <template #default="{ row }">
                  <el-button
                      size="mini"
                      type="text"
                      @click="handleUpdate(row)"
                  >
                      修改
                  </el-button>
              </template>
          </vxe-column>
        </vxe-table>

        <!-- 分页 -->
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    
        <!-- 底部表格 -->
        <!-- <div class="app-container-footer">
            <el-tabs  v-model="activeName" type="border-card" :lazy="true">
                <el-tab-pane label="会员收货信息" name="1">
                    <Address :cellId="cellId"  />
                </el-tab-pane>
                <el-tab-pane label="会员属性" name="2">
                    <Property :cellId="cellId"  />
                </el-tab-pane>
                <el-tab-pane label="会员消费统计" name="3">
                    <baseInfo :cellId="cellId" :poStatus="bottomTableData" />
                </el-tab-pane>
            </el-tabs>
        </div> -->
  
        <!-- 新增弹窗 -->
        <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="60%" append-to-body @close="cancel">
          <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row>
                <el-col :span="6">
                    <el-form-item label="会员名称" prop="clientName">
                        <el-input v-model="form.clientName" placeholder="请输入会员名称" />
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="会员编码" prop="clientCode">
                        <el-input v-model="form.clientCode" placeholder="请输入会员编码"  :disabled="form.clientId" />
                    </el-form-item>
                </el-col>
                  <el-col :span="6">
                    <el-form-item label="店铺名称" prop="shopId">
                        <el-select v-model="form.shopId" placeholder="请选择所属店铺">
                            <el-option
                                v-for="dict in shopList"
                                :key="dict.userId"
                                :label="dict.shopName"
                                :value="dict.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="6">
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="form.phone" placeholder="请输入手机号" />
                    </el-form-item>
                </el-col>
            </el-row>
            <!-- <el-row>
                <el-col :span="8">
                    <el-form-item label="会员来源" prop="shopType">
                        <el-input v-model="form.shopType" placeholder="请输入会员来源" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="所属店铺" prop="shopId">
                        <el-select v-model="form.shopId" placeholder="请选择所属店铺">
                            <el-option
                                v-for="dict in shopList"
                                :key="dict.userId"
                                :label="dict.shopName"
                                :value="dict.id"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="会员级别" prop="clientLevel">
                        <el-input v-model="form.clientLevel" placeholder="请输入会员级别" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="8">
                    <el-form-item label="QQ" prop="qq">
                        <el-input v-model="form.qq" placeholder="请输入QQ" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="业务员" prop="bizUser">
                        <el-select v-model="form.bizUser" placeholder="请选择业务员">
                            <el-option
                                v-for="dict in userList"
                                :key="dict.userId"
                                :label="dict.userName"
                                :value="dict.nickName"
                            />
                        </el-select>
                    </el-form-item>
                </el-col>
                
                <el-col :span="8">
                    <el-form-item label="真实姓名" prop="shipperAddress">
                        <el-input v-model="form.shipperAddress" placeholder="请输入真实姓名" />
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="16">
                    <el-form-item label="身份证号码" prop="creditCode">
                        <el-input v-model="form.creditCode" placeholder="请输入身份证号码" />
                    </el-form-item>
                </el-col>
                <el-col :span="2.6">
                    <el-form-item label="分销商" prop="distributor">
                        <el-checkbox v-model="form.distributor" />
                    </el-form-item>
                </el-col>
                <el-col :span="2.6">
                    <el-form-item label="黑名单" prop="blackFlag">
                        <el-checkbox v-model="form.blackFlag" />
                    </el-form-item>
                </el-col>
                <el-col :span="2.6">
                    <el-form-item label="停用" prop="enableFlag">
                        <el-checkbox v-model="form.enableFlag" />
                    </el-form-item>
                </el-col>
            </el-row> -->

            <el-row>
                <el-form-item label="备注" prop="remark">
                <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
            </el-row>
          </el-form>
          <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitForm">
                  {{  form.clientId ? '保 存' : '确 定' }}
              </el-button>
              <el-button @click="cancel">取 消</el-button>
          </div>
        </el-dialog>
  
        <!-- 导入对话框 -->
        <!-- <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
            <el-upload
                ref="upload"
                :limit="1"
                accept=".xlsx, .xls"
                :headers="upload.headers"
                :action="upload.url + '?updateSupport=' + upload.updateSupport"
                :disabled="upload.isUploading"
                :on-progress="handleFileUploadProgress"
                :on-success="handleFileSuccess"
                :auto-upload="false"
                drag
            >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                <div class="el-upload__tip text-center" slot="tip">
                    <span>仅允许导入xls、xlsx格式文件。</span>
                    <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
                </div>
            </el-upload>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitFileForm">确 定</el-button>
                <el-button @click="upload.open = false">取 消</el-button>
            </div>
        </el-dialog> -->

        <!-- 批量修改业务员 -->
        <!-- <el-dialog title="批量修改业务员" :visible="changeBizUser" width="400px" append-to-body>
            <el-select v-model="batchBizUser" placeholder="请选择业务员">
                <el-option
                    v-for="dict in userList"
                    :key="dict.userId"
                    :label="dict.userName"
                    :value="dict.nickName"
                />
            </el-select>

            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleChangeBizUser">确 定</el-button>
                <el-button @click="changeBizUser = false">取 消</el-button>
            </div>
        </el-dialog> -->
        
        <!-- 批量修改业务员 -->
        <!-- <el-dialog title="批量修改分销商" :visible="changeDistributor" width="400px" append-to-body>
            <el-radio-group v-model="batchDistributor">
                <el-radio label="false">否</el-radio>
                <el-radio label="true">是</el-radio>
            </el-radio-group>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="handleChangeDistributor">确 定</el-button>
                <el-button @click="changeDistributor = false">取 消</el-button>
            </div>
        </el-dialog> -->
    </div>
  </template>
  
  <script>
  import { 
    addMemberBasic,
    listMemberBasic,
    delMemberBasic,
    editMemberBasic,
    batchUpdateBizUser,
    batchUpdateDistributor,
    batchUpdateStatus
   } from "@/api/mes/sales/memberBasic";
   
  import { 
    listShopBasic,
   } from "@/api/mes/sales/shopBasic";

  import { getToken } from "@/utils/auth";
  import { listUser } from "@/api/system/user";
//   import {genCode} from "@/api/system/autocode/rule"
  import baseInfo from "./components/baseInfo.vue";
  import Address from "./components/address.vue";
  import Property from "./components/property.vue";
  
  export default {
    name: 'MemberBasic',
    components: { 
      baseInfo,
      Address,
      Property
    },
    data() {
      return {
        //自动生成编码
        autoGenFlag:false,
        title: '',
        open: false,
        loading: false,
        total: 0,
        form: {},
        rules: {
            // clientCode:[{ required: true, message: '请输入会员编码', trigger: 'blur' }],
            clientName:[{ required: true, message: '请输入会员名称', trigger: 'blur' }],
            shopId:[{ required: true, message: '请选择所属店铺', trigger: 'blur' }],
            phone:[{ required: true, message: '请输入手机号', trigger: 'blur' }],
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          poCode: null,
          vendorNick: null,
          poStatusList: undefined,
          poCheckStatusList: undefined,
        },
        tableDataList: [],
        vendorList: [],
        warehouseList: [],
        userList: [],
        shopList: [],
        activeName: '1',
        cellId: null, //当前选中单元格的id
        baseTotal: 0, //采购订单条数
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/mes/md/shop/importData"
        },
        columnConfig: {
          drag: true,
          resizable: true,
          storage: true,
          sortConfig: {
            trigger: 'cell',
            remote: true
          },
          align: 'center',
          headerAlign: 'center'
        },
        rowConfig: {
          drag: true,
          keyField: 'clientId',
          isHover: true,
          isCurrent: true,
        },
        ids: [], //选中的条目
        bottomTableData: '', //采购订单状态
        changeBizUser: false,
        changeDistributor: false,
        batchBizUser: '',
        batchDistributor: '',
      }
    },
    created() {
      this.getList()
      listUser({ pageNum: 1, pageSize: 9999 }).then(response => {
        this.userList = response.rows;
      })
      listShopBasic({ pageNum: 1, pageSize: 9999, enabled: 1 }).then(response => {
        this.shopList = response.rows; 
      })
    },
    methods: {
      getList(){
        this.loading = true;
        listMemberBasic(this.queryParams).then(response => {
          this.tableDataList = response.rows;
          this.$nextTick(() => {
            this.$refs.tableRef.setCurrentRow(this.tableDataList[0]);
          })
          if(response.rows?.length>0){
            this.cellId = response.rows[0].clientId;
          }
          this.total = response.total;
          console.log(response);
        }).finally(() => {
          this.loading = false;
        })
      },
      reset(){
        this.form = {};
        this.autoGenFlag = false;
      },
      handleAdd(){
        this.open = true;
        this.title = '新增';
        this.reset()
      },
      handleDelete(row){
        if(this.ids.length==0){
          this.$modal.msgError("请选择要删除的数据");
          return;
        }
        const ids = this.ids;
        this.$modal.confirm('是否确认删除该数据项？').then(function() {
          return delMemberBasic(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      handleUpdate(row){
        this.title = '修改';
        this.reset();
        this.form = { 
            ...row,
            phone: row.phone && row.phone!= 'null' ? row.phone : '',
        };
        this.open = true;
      },
      handleToExamine(row){
        console.log(row);
      },
      handleAntiAudit(row){
        console.log(row);
      },
      handleQuery(){
        this.queryParams.pageNum = 1;
        this.getList();
      },
      resetQuery(){
        this.resetForm("queryForm");
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          poCode: null,
          vendorNick: null,
          poStatusList: undefined,
          poCheckStatusList: undefined,
        },
        this.getList();
      },
      submitForm(){
        this.$refs["form"].validate(valid => {
          if (valid) {
            const params = {
                ...this.form,
                // distributor: this.form.distributor ? 'Y' : 'N',
                // enableFlag: this.form.enableFlag ? 'Y' : 'N',
                // blackFlag: this.form.blackFlag ? 'Y' : 'N',
            }
            if (this.form.clientId) {
                editMemberBasic(params).then(response => {
                    this.$modal.msgSuccess("修改成功");
                    this.open = false;
                    this.getList();
                });
            } else {
              addMemberBasic(params).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        })
      },
      cancel(){
        this.$refs["form"].resetFields();
        this.open = false;
      },
      cellClickEvent({row}){
        this.cellId = row.clientId;
        this.handleClick({name:'1'})
      },
      checkboxChangeEvent(checked){
        this.ids = checked.records.map(item => item.clientId)
      },
      checkboxAll(checked){
        this.ids = checked.records.map(item => item.clientId)
      },
      handleClick(tab, event) {
        switch (tab.name) {
          case '1':
            // console.log('基础信息');
            break;
          case '2':
            console.log('2');
            break;
          default:
            break;
        }
      },
      handleUpload(){
        this.upload.title = "数据导入";
        this.upload.open = true;
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
        this.getList();
      },
      handlePrint(row){
        console.log(row, window.location);
        window.open(window.location.origin + window.location.pathname + '#/printTemplate?poId=' + row.id + '&type=in', '_blank');
      },
      importTemplate(){
        window.open("/excel_templates/shop_templates.xls", "_blank"); 
      },
      handleChange(type){
        if(this.ids.length==0){
          this.$modal.msgError("请选择数据");
          return;
        }
        this.changeBizUser = type == 'bizUser' ? true : false;
        this.changeDistributor = type == 'distributor' ? true : false;
      },
      closeHandle(){
        this.changeBizUser = false;
        this.changeDistributor = false;
        this.batchBizUser = '';
        this.batchDistributor = '';
      },
      handleChangeBizUser(){
        if(this.batchBizUser == ''){
          this.$modal.msgError("请选择业务员");
          return;
        }
        batchUpdateBizUser({
            clientIds: this.ids,
            bizUser: this.batchBizUser,
        }).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.closeHandle();
            this.getList();
        });
      },
      handleChangeDistributor(){
        if(this.batchDistributor == ''){
          this.$modal.msgError("请选择是否分销商");
          return;
        }
        batchUpdateDistributor({
            clientIds: this.ids,
            distributor: this.batchDistributor === 'true' ? 'Y' : 'N',
        }).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.closeHandle();
            this.getList();
        });
      },
      handleEnable(val){
        if(this.ids.length == 0){
          this.$modal.msgError("请选择数据");
          return;
        }
        this.$confirm('确定要修改吗？').then(() => {
            batchUpdateStatus({
                clientIds: this.ids,
                enable: val,
            }).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.getList();
          });
        }) 
      },
    }
  }
  </script>
  
  <style lang="scss" scoped>
    .el-select{
      width: 100%;
    }
  </style>